package com.fluxtool.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.plugins.Page;
import com.fluxtool.entity.Ips;
import com.fluxtool.service.IpsService;


@Controller
@RequestMapping("/ip")
public class IpsController {
	
	static String URL = "http://api.xicidaili.com/free2016.txt";
	
	private static final Logger log = LoggerFactory.getLogger(IpsController.class);

	@Autowired
	private IpsService ipsService;
	
	@RequestMapping("/ips")
	public String ipsIndex(Model model, Page<Ips> page){
		Page<Ips> pages  = ipsService.selectPage(page);
		model.addAttribute("pages", pages);
		return "ips";
	}
	
	
	@RequestMapping("/ipadd")
	public String ipAdd(int id, Model model){
		if(id!=0){
			Ips ip = ipsService.selectById(id);
			model.addAttribute("ip", ip);
		}
		return "ipadd";
	}
	
	@RequestMapping("/insertOrUpdate")
	public String saveIp(Ips ip){
		ipsService.insertOrUpdate(ip);
		return "ips";
	}
	
	@RequestMapping("/delete")
	public String deleteIp(Long id){
		ipsService.deleteById(id);
		return "ips";
	}
	
	
	@RequestMapping("/getIps")
	public String getIps(){
		List<Ips> list = null;
		try {
			//1.向ip代理地址发起get请求，拿到代理的ip
			Document doc = Jsoup.connect(URL)
			  .userAgent("Mozilla")
			  .cookie("auth", "token")
			  .timeout(3000)
			  .get();
			
			//2,将得到的ip地址解析除字符串
			String ipStr = doc.body().text().trim().toString();
			
			//3.用正则表达式去切割所有的ip
			String[] ips = ipStr.split("\\s+");
			
			//4.循环遍历得到的ip字符串，封装成MyIp的bean
			list = new ArrayList<Ips>();
			for(final String ip : ips) {
				Ips _ip = new Ips();
				String[] temp = ip.split(":");
				_ip.setIp(temp[0].trim());
				_ip.setPort(temp[1].trim());
				_ip.setEnble(1);
				list.add(_ip);
			}
			if(list.size()>0){
				ipsService.deleteALL();
			}
			ipsService.insertBatch(list);
			log.info("ips更新成功");
		} catch (IOException e) {
			log.info("加载文档出錯");
		}
		return "ips";	
	}
	
}
